package com.pscsoft.lucene.utils;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import java.io.IOException;
import java.nio.file.Paths;

public class LuceneUtils {

    final static String store_path = "data/store_path";

    private LuceneUtils() {
    }

    static IndexWriter indexWriter = null;

    public static IndexWriter getIndexWrite() {

        try {
            Directory directory = FSDirectory.open(Paths.get(store_path));
            Analyzer analyzer = new StandardAnalyzer();
            IndexWriterConfig conf = new IndexWriterConfig(analyzer);
            indexWriter = new IndexWriter(directory, conf);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indexWriter;
    }

    public static void indexWriterClose() {
        if (indexWriter != null) {
            try {
                indexWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void searchData(Query query) {
        TopDocs topDocs = null;
        IndexReader reader = null;
        IndexSearcher searcher = null;
        try {
            Directory directory = FSDirectory.open(Paths.get(store_path));
            reader = DirectoryReader.open(directory);
            searcher = new IndexSearcher(reader);
            topDocs = searcher.search(query, 10);
            System.out.println("本次搜索共找到" + topDocs.totalHits + "条数据");
            ScoreDoc[] scoreDocs = topDocs.scoreDocs;

            for (ScoreDoc scoreDoc : scoreDocs) {
                int docID = scoreDoc.doc;
                Document doc = reader.document(docID);
                System.out.println("value: " + doc.get("value"));
                System.out.println("得分： " + scoreDoc.score);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
